package org.glut.wechat.addresslist.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.glut.wechat.addresslist.entity.Relation;
import org.glut.wechat.addresslist.entity.Request;
import org.glut.wechat.addresslist.mapper.RequestMapper;
import org.glut.wechat.addresslist.service.IRelationService;
import org.glut.wechat.addresslist.service.IRequestService;
import org.glut.wechat.addresslist.vo.RequestVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 申请添加好友表 服务实现类
 *
 * @author harry
 * @since 2025-08-21 20:25
 */
@Service
public class RequestServiceImpl extends ServiceImpl<RequestMapper, Request> implements IRequestService {
    @Resource
    private IRelationService relationService;

    // 获取待处理申请
    public List<RequestVO> getNewRequests(Integer toUserId) {
        return baseMapper.getNewRequests(toUserId);
    }

    // 同意申请：更新状态
    @Transactional(rollbackFor = Exception.class)
    public boolean agreeRequest(Integer requestId) {
        Request request = getById(requestId);
        if (request == null || request.getStatus() != 0) return false;

        // 更新申请状态为1
        request.setStatus(1);
        boolean success = updateById(request);

        // 插入双向好友关系到表
        if (success) {
            Integer fromUserId = request.getFromUserId();
            Integer toUserId = request.getToUserId();
            // 被申请人加申请人为好友
            Relation relation1 = new Relation();
            relation1.setUserId(toUserId);
            relation1.setFriendId(fromUserId);
            relation1.setStatus(1); // 正常
            relation1.setCreateTime(new Date());
            relationService.save(relation1);

            //申请人加被申请人为好友
            Relation relation2 = new Relation();
            relation2.setUserId(fromUserId);
            relation2.setFriendId(toUserId);
            relation2.setStatus(1); // 正常
            relation2.setCreateTime(new Date());
            relationService.save(relation2);
        }
        return success;
    }

    // 忽略申请：更新状态为2
    public boolean ignoreRequest(Integer requestId) {
        Request request = getById(requestId);
        if (request == null || request.getStatus() != 0) return false;

        request.setStatus(2); // 已忽略
        return updateById(request);
    }
}
